package com.tsystems.school;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;

/**
 * @author Yuri Denison; yuri.denison@gmail.com
 * @since 30.06.11
 */

public class Main {

    public static void main(String args[]) throws IOException {
        PropertyConfigurator.configure("resources/log4j.properties");
        Logger logger = Logger.getLogger(Main.class);

        logger.debug("Analyzing input args...");
        if (args.length != 2) {
            logger.error("Incorrect parameters. They should be 'input filename' 'output path'.");
            return;
        }
        String inputFileName = args[0];
        String outputPath = args[1];
        logger.debug("Done.");

        PrintWriter out1;
        PrintWriter out2;
        BufferedReader br;
        logger.debug("Initing I/O...");
        try {
            br = new BufferedReader(new FileReader(inputFileName));
            new File(outputPath).mkdirs();
            out1 = new PrintWriter(new FileWriter(outputPath + "out1.txt"));
            out2 = new PrintWriter(new FileWriter(outputPath + "out2.txt"));
        } catch (FileNotFoundException e) {
            logger.error("Bad input filename or bad output path.");
            return;
        } catch (Exception e) {
            logger.error("Error stack trace", e);
            return;
        }
        logger.debug("Done.");

        logger.debug("Filling HashMap...");
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        String cur;
        while ((cur = br.readLine()) != null) {
            cur = cur.trim();
            logger.trace("Add new string: " + cur);
            if (!cur.equals("")) {
                if (map.containsKey(cur)) {
                    map.put(cur, map.get(cur) + 1);
                } else {
                    map.put(cur, 1);
                }
            }
        }
        logger.debug("Done.");

        logger.debug("Starting form the output...");
        Vector<String> v = new Vector<String>(map.keySet());
        Collections.sort(v);
        for (String line : v) {
            out1.printf("%s\n", line);
            int num;
            if ((num = map.get(line)) > 1) {
                out2.printf("%s - %d\n", line, num);
            }
        }
        logger.debug("Done.\n");

        br.close();
        out1.close();
        out2.close();
    }

}
